package com.project.service.impl;

import com.project.bean.RecordBean;
import com.project.bean.UserBean;
import com.project.mapper.IRecordMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalTime;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper mapper;
    @Autowired
    private IRecordMapper recordMapper;

    @Override
    public UserBean login(String code, String psw) {
        UserBean user = mapper.login(code,psw);
        if (user != null){
            RecordBean record = new RecordBean("用户" + code + "在" + LocalTime.now() + "登录系统");
            recordMapper.addRecord(record);
            return user;
        }
        return null;
    }

    @Override
    public boolean add(UserBean user) {
        UserBean userBean = mapper.checkCode(user.getCode());
        if (userBean == null){
            mapper.add(user);
            return true;
        }
        return false;
    }

    @Override
    public void del(int id) {
        mapper.del(id);
    }

    @Override
    public UserBean findById(int id) {
        UserBean user = mapper.findById(id);
        return user;
    }

    @Override
    public void updateGrade(int id, String grade) {
        mapper.updateGrade(id,grade);
    }

    @Override
    public List<UserBean> findByGrade(String grade) {
        List<UserBean> list = mapper.findByGrade(grade);
        return list;
    }

    @Override
    public boolean updatePsw(int id, String oldPsw, String newPsw) {
        UserBean user = mapper.findById(id);
        if (oldPsw.equals(user.getPsw())){
            mapper.updatePsw(id,newPsw);
            return true;
        }
        return false;
    }
}
